package com.itec.learn.java.design.observer.jive;

import java.util.*;

/**
 * 邮件通知观察者
 * @author chenyiqun
 */
public class EmailWatchManager implements WatchManager {

    private ForumFactory factory;

    public EmailWatchManager(ForumFactory factory){
        this.factory = factory;
    }

    //观察者列表，ForumThread id 作为key
    private Map<Integer, List<User>> watches = new HashMap<Integer, List<User>>();

    /**
     * 添加观察者
     * @param user
     * @param thread
     */
    @Override
    public void createWatch(User user, ForumThread thread) {
        List<User> users = watches.get(thread.getId());
        if (users == null || users.isEmpty()) {
            users = new ArrayList<User>();
            watches.put(thread.getId(),users);
        }
        users.add(user);
    }

    protected void notifyWatches(ForumThread thread) {
        //通知观察者，将任务加入线程池
        List<User> users = watches.get(thread.getId());
        if (!users.isEmpty()) {
            for (User user:users){
                System.out.println(String.format("[%s] 用户， 主题 [%s] 有新的消息！",user.getName(),thread.getTitle()));
            }
        }
    }
}
